package net.onceface.application.impl;

import java.util.List;

import javax.inject.Named;

import org.springframework.transaction.annotation.Transactional;

import net.onceface.application.ClientApplication;
import net.onceface.application.assembler.ClientAssembler;
import net.onceface.application.assembler.PersonAssembler;
import net.onceface.application.commons.InvokeResult;
import net.onceface.application.dto.ClientDTO;
import net.onceface.core.domain.Client;
import net.onceface.infra.querychannel.QueryChannelService;
import net.onceface.infra.spring.ioc.InstanceFactory;

@Named
@Transactional
public class ClientApplicationImpl implements ClientApplication {

	private QueryChannelService queryChannel;
	
	private QueryChannelService getQueryChannelService() {
		if (queryChannel == null) {
			queryChannel = InstanceFactory.getInstance(
					QueryChannelService.class, "queryChannel");
		}
		return queryChannel;
	}
	@Override
	public ClientDTO getClient(Long id) {
		return ClientAssembler.toDTO(Client.get(Client.class, id));
	}

	@Override
	public void saveClient(ClientDTO clientDTO) {
		Client client = ClientAssembler.toEntity(clientDTO);
		client.setPerson(PersonAssembler.toEntity(clientDTO.getPerson()));
		client.save();
	}

	@Override
	public void updateClient(ClientDTO clientDTO) {
		Client client = ClientAssembler.toEntity(clientDTO);
		//client.setPerson(PersonAssembler.toEntity(clientDTO.getPerson()));
		client.save();
	}

	@Override
	public void removeClient(ClientDTO clientDTO) {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeClients(List<ClientDTO> clientDTOs) {
		// TODO Auto-generated method stub

	}

	@Override
	public List<Client> findAllClient() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 登陆专用，不能修改
	 * ***/
	@Override
	public ClientDTO findAvailableClientByUserAccount(String userAccount) {
		StringBuilder jpql = new StringBuilder("SELECT new net.onceface.application.dto.ClientDTO(_client.userAccount,_client.userPassword,_client.salt,_client.disabled) FROM Client _client")
		.append(" WHERE _client.userAccount = :userAccount")
		.append(" AND _client.disabled > 0")
		.append(" AND _client.abolishDate > NOW()");
		return (ClientDTO) getQueryChannelService().createJpqlQuery(jpql.toString())
				.addParameter("userAccount", userAccount).singleResult();
	}
	
	@Override
	public InvokeResult findClientByAccount(String userAccount) {
		ClientDTO client = ClientAssembler.toDTO(Client.findByUserAccount(userAccount));
		client.setUserPassword(null);
		return InvokeResult.success(client);
	}

}
